//
//  Avatar+UserNameSetViewController.swift
//  ShiZhe
//
//  Created by 陈卿伟 on 16/9/6.
//  Copyright © 2016年 陈卿伟. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON



class Avatar_UserNameSetViewController: MainViewController {
    var AUView:Avatar_UserNameView!
    var cameraView:CameraView!//调用相册和相机的view

    override func viewDidLoad() {
        super.viewDidLoad()
       self.title = "资料填写"
        self.addViewToControll()
        self.addTargetForView()
    }
}

//MARK:--UI
extension Avatar_UserNameSetViewController{
    //添加view进来
    func addViewToControll(){
        AUView = Avatar_UserNameView(frame: MainBounds)
        self.view.addSubview(AUView)
    }
    
    //为控件添加点击事件
    func addTargetForView(){
        //设置头像按钮
        AUView.cameraButton.addTarget(self, action: #selector(self.cameraButtonClick(_:)), forControlEvents: .TouchUpInside)
        //确定按钮
        AUView.beganButton.addTarget(self, action: #selector(self.beganButtonClick(_:)), forControlEvents: .TouchUpInside)
    }
}

//MARK:--点击事件
extension Avatar_UserNameSetViewController{
    //设置头像点击事件
    func cameraButtonClick(sender:UIButton){
        cameraView = CameraView(frame: MainBounds)
        self.view.window!.addSubview(cameraView)
        cameraView.albumButton.addTarget(self, action: #selector(self.setAlbumButtonClick(_:)), forControlEvents: .TouchUpInside)
        cameraView.cameraButton.addTarget(self, action: #selector(self.setCameraButtonClick(_:)), forControlEvents: .TouchUpInside)
    }
    
    //确定点击事件
    func beganButtonClick(sender:UIButton){
        if let hud = self.view.window!.viewWithTag(999) as? WaitHUD{
            hud.alpha = 1
            setAvatarAndUserNameAlamofire(hud)
        }
    }
    
    //使用相机点击事件
    func setCameraButtonClick(sender:UIButton){
        cameraView.animateForCameraView()
        if UIImagePickerController.isSourceTypeAvailable(.Camera){
            let picker = UIImagePickerController()
            picker.delegate = self
            picker.sourceType = UIImagePickerControllerSourceType.Camera
            picker.allowsEditing = true
            self.presentViewController(picker, animated: true, completion: { () -> Void in
            })
        }else{
            showHUD.showTopHud(self.view, text: "调用相机出错")
        }
    }
    
    //使用相册点击事件
    func setAlbumButtonClick(sender:UIButton){
        cameraView.animateForCameraView()
        if UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary){
            let picker = UIImagePickerController()
            picker.delegate = self
            picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
            picker.allowsEditing = true
            self.presentViewController(picker, animated: true, completion: {
                () -> Void in
            })
        }else{
            showHUD.showTopHud(self.view, text: "读取相册错误")
        }
    }
}

//MARK:--相机和相册代理 delegate
extension Avatar_UserNameSetViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    //选择图片成功后代理
    func imagePickerController(picker: UIImagePickerController,didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        //获取选择的原图
        var imageX:UIImage!
        if(picker.allowsEditing){
            //裁剪后图片
            imageX = info[UIImagePickerControllerEditedImage] as! UIImage
        }else{
            //原始图片
            imageX = info[UIImagePickerControllerOriginalImage] as! UIImage
        }
        //图片控制器退出
        picker.dismissViewControllerAnimated(true, completion: {
            () -> Void in
            self.AUView.cameraButton.setBackgroundImage(imageX, forState: .Normal)
            self.AUView.cameraButton.layer.cornerRadius = 50*SCALEW
        })
    }
}


//MARK:--Alamofire
extension Avatar_UserNameSetViewController{
    //上传图片和用户名Alamofire
    func setAvatarAndUserNameAlamofire(hud:WaitHUD){
        var imageData:NSData!
        var userNameData:NSData!
        if let avatar = self.AUView.cameraButton.backgroundImageForState(.Normal){
            imageData = UIImageJPEGRepresentation(avatar, 0.01)!
        }else{
            imageData = UIImageJPEGRepresentation(UIImage(named: "noAvatar")!, 0.01)
        }
        if let userNameString = self.AUView.userNameTF.text{
            userNameData = userNameString.dataUsingEncoding(NSUTF8StringEncoding)
        }else{
            userNameData = "YOUKNOWWHO".dataUsingEncoding(NSUTF8StringEncoding)
        }
        let token = OperateUserDefaults.takeUserInfo().token
        Alamofire.upload(.POST, "http://srxapp.zhekd.com/ios.php/Login/set_user_image", headers: ["token":token], multipartFormData: { (multipartFormData) in
            multipartFormData.appendBodyPart(data: imageData, name: "head_image", fileName: "avatar.jpg", mimeType: "image/jpeg")
            multipartFormData.appendBodyPart(data: userNameData, name: "user_name")
            }, encodingCompletion: { (manager) in
                switch manager{
                case .Success(request: let request, streamingFromDisk: _, streamFileURL: _):
                    request.responseJSON(completionHandler: { (data) in
                        let json = JSON(data: data.data!)
                        let code = json["code"].stringValue
                        let message = json["message"].stringValue
                        if code == "1"{
                            dispatch_async(dispatch_get_main_queue(), {
                                hud.alpha = 0
                            NSNotificationCenter.defaultCenter().postNotificationName(Notifiction.LOGIN, object: nil)
                                self.navigationController?.popToRootViewControllerAnimated(true)
                            })
                        }else{
                            showHUD.showTopHud(self.view, text: message)
                        }
                    })
                case .Failure(let error):
                    debugPrint(error)
                }
        })
    }
    
}














